package com.wcy.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * <p>Title:AutoFillHandler.java</p >
 * <p>Description: </p >
 * <p>Copyright: 公共服务与应急管理战略业务本部 Copyright(c)2020</p >
 * <p>Date:2021/9/20 13:27</p >
 *
 * @author wcy (wangchaoyanga@mail.taiji.com.cn)
 * @version 1.0
 */
@Component
public class AutoFillHandler implements MetaObjectHandler {

    /**
     * 插入元对象字段填充
     *  新增数据时需要填充
     *             创建人
     *             创建时间
     *             最后更新时间
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId=getCurrentUserId();
        this.strictInsertFill(metaObject,"created",Date.class,new Date());
        this.strictInsertFill(metaObject,"createBy",Long.class,userId);
        this.strictInsertFill(metaObject,"lastUpdateTime",Date.class,new Date());

    }

    /**
     * 修改数据时的填充
     *           修改人
     *           修改时间
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId=getCurrentUserId();
        this.strictUpdateFill(metaObject,"modifyBy",Long.class,userId);
        this.strictUpdateFill(metaObject,"lastUpdateTime",Date.class,new Date());
    }

    /**
     * 获取当前操作的用户对象
     */
    public Long getCurrentUserId(){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if(authentication!=null){
            return Long.valueOf(authentication.getName());
        }
        return null;
    }
}
